package com.app.mingluxing.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.HomeAdapter;
import com.app.mingluxing.base.BaseFragment;
import com.app.mingluxing.bean.BabayTreeData;
import com.app.mingluxing.bean.BabyTreeRes;
import com.app.mingluxing.bean.BindChildList1;
import com.app.mingluxing.bean.RequestSimpleBean;
import com.app.mingluxing.bean.UploadBean;
import com.app.mingluxing.home.ChooseHomeBabyActivity;
import com.app.mingluxing.home.InviteActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.pull2refush.PullToRefreshBase;
import com.app.mingluxing.pull2refush.PullToRefreshListView;
import com.app.mingluxing.ui.BindChildActivity;
import com.app.mingluxing.ui.HomeActivity;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.zxing.CaptureActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * 首页fragment
 * Created by Aaron on 2015/7/20.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {
//    public static final int SCAN_CODE = 1;
    private int currentPageNum;
    private List<BabayTreeData> babayTreeDatas = new ArrayList<BabayTreeData>();
    private PullToRefreshListView plv_friend;
    private HomeAdapter homeAdapter;
    private Intent mIntent;
    //缓存当前的宝宝id
//    private String cacheChildId = "";
//    private List<BindChildList.Data> children;
    private ImageView iv_bgImgUrl;
    private TextView tv_ageLine;
    private TextView tv_timeLine;
    private TextView tv_title;
    //    private String imageUrl;
    public DisplayImageOptions options;
    /*拍照的文件保存的位置*/
//    private File currentFile;
//    /*相册选择的code*/
//    private static final int PHOTO_ALBUM_CODE_HOME = 10031;
//    /*拍照的code*/
//    private static final int TAKE_PHOTO_CODE_HOME = 10032;
//    //当前选中的宝宝id
//    private String currentChildId;
    private String currentChildId;
    private ListView listView;
    //    private int level;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        EventBus.getDefault().register(this);

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

//        ShareSDK.stopSDK(getActivity());

        LogUtil.e("tag", "=== homefragemnt   ondestory ===");

        EventBus.getDefault().unregister(this);

//        mApplication.cancelPendingRequests(getClass().getName());

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, null);
//        babayTreeDatas = new ArrayList<BabayTreeData>();
        currentChildId = sp.getString(Constant.CURRENTCHILDID, "");
//        level = sp.getInt(Constant.LEVEL, -1);
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.home_bg)
                .showImageForEmptyUri(R.drawable.home_bg)
                .showImageOnFail(R.drawable.home_bg)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        initWidget(view);

        homeAdapter.setFragmentView(view);

        currentPageNum = 0;

        if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {//如果没有当前选中的宝宝id

            getChildList();

        } else {
            //获取首页数据
            getHomeData();
        }

        LogUtil.e("tag", "===== oncreateview ====");

//        else {//绑定的宝宝集合有数据 则用id请求宝宝树内容
//
////            if (mApplication.bindChildList.size() == 0) {
////                showToast("未查询到宝宝信息");
////                return view;
////            }
////            mApplication.currentChildId = mApplication.bindChildList.get(0).id;
//            if (babayTreeDatas != null)
//                babayTreeDatas.clear();
////            //获取首页数据
////            getHomeData();
//
//        }
        return view;
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//
//        ShareSDK.initSDK(getActivity());
//
//    }

    /**
     * 发布了新的消息, 更新页面
     * @param event
     */
    public void onEventMainThread(Integer event) {

        if (babayTreeDatas != null)
            babayTreeDatas.clear();
        currentPageNum = 0;
        getHomeData();

    }

    private void initWidget(View view) {

        plv_friend = (PullToRefreshListView) view.findViewById(R.id.plv_friend);

        listView = plv_friend.getRefreshableView();

        View headView = View.inflate(getActivity(), R.layout.layout_home_head, null);

        iv_bgImgUrl = (ImageView) headView.findViewById(R.id.iv_bgImgUrl);
        tv_ageLine = (TextView) headView.findViewById(R.id.tv_ageLine);
        tv_timeLine = (TextView) headView.findViewById(R.id.tv_timeLine);
        iv_bgImgUrl.setOnClickListener(this);
        listView.addHeaderView(headView);
        homeAdapter = new HomeAdapter(getActivity(), babayTreeDatas);
        listView.setAdapter(homeAdapter);

        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText(getActivity().getResources().getString(R.string.home));

        RelativeLayout title = (RelativeLayout) view.findViewById(R.id.title);
        title.setOnClickListener(this);

        ImageView iv_right = (ImageView) view.findViewById(R.id.iv_right);
        ImageView iv_left = (ImageView) view.findViewById(R.id.iv_left);

        TextView tv_invite_code = (TextView) view.findViewById(R.id.tv_invite_code);
        plv_friend.setMode(PullToRefreshBase.Mode.BOTH);
        plv_friend.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                currentPageNum = 0;

                if (babayTreeDatas != null)
                    babayTreeDatas.clear();

                getHomeData();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                ++currentPageNum;

                getHomeData();
            }
        });
        iv_right.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        tv_invite_code.setOnClickListener(this);
    }

    /**
     * 获取首页数据
     */
    private void getHomeData() {

//        MessageReqBean reqBean = new MessageReqBean();
//        reqBean.token = sp.getString(Constant.TOKEN, "");
//        reqBean.pageNum = currentPageNum + "";

        if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
//            showToast("请先选择宝宝");
            return;
        }

//        reqBean.id = sp.getString(Constant.CURRENTCHILDID, "");

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("pageNum", currentPageNum + "");
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));

        HttpUtil.setPostRequest("获取中...", getActivity(), Constant.WEB_ROOT + Constant.GETTREE, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                plv_friend.onRefreshComplete();

                try {
                    BabyTreeRes babyTreeRes = JSONObject.parseObject(str, BabyTreeRes.class);
                    if (babyTreeRes.code == Constant.STATUS_SUCCESS) {

                        //设置head 数据
                        tv_ageLine.setText(babyTreeRes.ageLine);
                        tv_timeLine.setText(babyTreeRes.timeLine);

                        ImageLoader.getInstance().displayImage(babyTreeRes.bgImgUrl, iv_bgImgUrl, options);

                        if (babyTreeRes.data != null) {

                            if (babyTreeRes.data.size() == 0) {
                                babayTreeDatas = babyTreeRes.data;

                                if (currentPageNum > 0) {
                                    showToast("当前已经是最后一页");
                                    return;
                                }

                            }

                            setDataView(babyTreeRes.data);
                            homeAdapter.setData(babayTreeDatas);
                            homeAdapter.notifyDataSetChanged();
                        }

                    } else {
                        showToast(Constant.showErrorMsg(babyTreeRes.code, getActivity()));
                    }
                } catch (Exception e) {
                    showToast(Constant.NODATA);
                    e.printStackTrace();
                }


            }
        }, new HttpUtil.FailListener() {

            @Override
            public void setOnFailListener() {
                plv_friend.onRefreshComplete();

                    //如果是请求第一页数据出错的话 清空listview
                if (currentPageNum == 0 && homeAdapter != null && babayTreeDatas!=null) {
                    babayTreeDatas.clear();
                    homeAdapter.setData(babayTreeDatas);
                    homeAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_right:

                //切换宝宝
                mIntent = new Intent(getActivity(), ChooseHomeBabyActivity.class);
                getActivity().startActivity(mIntent);
                break;

            case R.id.iv_left://扫码二维码绑定班级
                mIntent = new Intent(getActivity(), CaptureActivity.class);
                getActivity().startActivity(mIntent);
                break;

            case R.id.tv_invite_code://邀请码

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast("请先选择宝宝");
                    return;
                }

                //邀请码
                mIntent = new Intent(getActivity(), InviteActivity.class);
                mIntent.putExtra("childId", sp.getString(Constant.CURRENTCHILDID, ""));
                getActivity().startActivity(mIntent);

                break;
            case R.id.iv_bgImgUrl: //切换首页背景图片

                if (Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, -1)) {

                    HomeActivity home = (HomeActivity) getActivity();
                    home.showHomeChoose();

                } else {
                    showToast("无权限");
                }

                break;

            case R.id.title: // 回到顶部

//                LogUtil.e("tag", "回到顶部");

//                listView.sets

                if (!listView.isStackFromBottom()) {
//                    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
                    listView.setStackFromBottom(true);
                }
                listView.setStackFromBottom(false);

                break;

        }

    }

    protected void setDataView(List<BabayTreeData> temp) {

//        if (babayTreeDatas.size() == 0) {
//            babayTreeDatas = temp;
//            return;
//        }

        int nowSize = babayTreeDatas.size();
        int newSize = temp.size();
        for (int i = 0; i < newSize; i++) {
            boolean exist = true;
            BabayTreeData mcod = temp.get(i);
            for (int j = 0; j < nowSize; j++) {
                BabayTreeData nmcod = babayTreeDatas.get(j);
                if (mcod.tree.id.equals(nmcod.tree.id)) {
                    exist = false;
                    break;
                }
            }
            if (exist)
                babayTreeDatas.add(mcod);

        }
    }

    /**
     * 获取宝宝列表
     */
    private void getChildList() {

        RequestSimpleBean requestSimpleBean = new RequestSimpleBean();
        requestSimpleBean.token = sp.getString(Constant.TOKEN, "");
        HttpUtil.setPostRequest("获取宝宝列表中...", getActivity(), Constant.WEB_ROOT + Constant.GETCHILDERNANDEWATCH, JSONObject.toJSONString(requestSimpleBean),
                getClass().getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {
                try {

                    BindChildList1 bindChild = JSONObject.parseObject(str, BindChildList1.class);

                    if (bindChild.code == Constant.STATUS_SUCCESS) {

                        List<BindChildList1.Data> children = bindChild.data;
                        if (children == null || children.size() == 0) {

                            mIntent = new Intent(getActivity(), BindChildActivity.class);
                            startActivity(mIntent);
                            return;
                        }
                        //默认显示第一个宝宝
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(Constant.CURRENTCHILDID, children.get(0).id);
                        edit.putString(Constant.CURRENTCHILDNAME, children.get(0).name);
                        edit.putInt(Constant.LEVEL, children.get(0).level);

                        edit.apply();
                        getHomeData();

                    } else {
                        showToast(Constant.showErrorMsg(bindChild.code, getActivity()));
                    }

                } catch (Exception e) {
                    showToast(Constant.NODATA);
                    e.printStackTrace();
                    LogUtil.e("TAG", "获取学校宝宝联系人数据解析错误");
                }
            }
        }, null);

    }

    /**
     * 更换孩子图片背景
     *
     * @param imageUrl 图片的网络地址
     */
    private void updateChildInfo(final String imageUrl) {

        JSONObject j = new JSONObject();
        j.put("id", currentChildId);
        j.put("bgImgUrl", imageUrl);
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("更改中...", getActivity(), Constant.WEB_ROOT + Constant.UPDATECHILDINFO, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                if (CommonUtils.isNull(str)) {
                    showToast(Constant.NODATA);
                    return;
                }

                try {

                    org.json.JSONObject result = new org.json.JSONObject(str);

                    if (result.getInt("code") == Constant.STATUS_SUCCESS) {

                        //更改完成后 修改背景图片 后台默认 在 原图片上 + "_m"
                        ImageLoader.getInstance().displayImage(imageUrl + "_m", iv_bgImgUrl, options);

                    } else {

                        showToast(Constant.showErrorMsg(result.getInt("code"), getActivity()));

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(Constant.NODATA);
                }
            }
        }, null);
    }
    /**
     * 获取图片上传的token
     *
     * @param bytes 图片的字节流
     */
    public void getUploadToken(final byte[] bytes) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("加载中...", getActivity(), Constant.WEB_ROOT + Constant.UPLOADTOKEN, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                final UploadBean uploadBean = JSONObject.parseObject(str, UploadBean.class);

                if (uploadBean.code == Constant.STATUS_SUCCESS) {

                    UploadManager uploadManager = new UploadManager();

                    uploadManager.put(bytes, uploadBean.path, uploadBean.token,

                            new UpCompletionHandler() {
                                @Override
                                public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                                    if (responseInfo.isOK()) {

                                        updateChildInfo(uploadBean.domain + uploadBean.path);

                                    } else {

                                        showToast("图片上传失败");

                                    }

                                }

                            }, null);

                } else {
                    showToast(Constant.showErrorMsg(uploadBean.code, getActivity()));
                }

            }
        }, null);
    }

}